/**
 * 文档智能摘要工具 - 客户端脚本
 * 包含所有页面共用的基础功能
 */

// 主题管理
const themeManager = {
    // 初始化主题
    init() {
        const savedTheme = localStorage.getItem('theme') || 'system';
        this.setTheme(savedTheme);
        
        // 主题切换按钮
        const themeToggle = document.getElementById('theme-toggle');
        const themeLabel = document.getElementById('theme-label');
        
        if (themeToggle && themeLabel) {
            // 根据当前主题设置切换按钮状态
            const isDark = document.body.classList.contains('dark-theme');
            themeToggle.checked = isDark;
            themeLabel.textContent = isDark ? '亮色模式' : '暗色模式';
            
            // 监听主题切换
            themeToggle.addEventListener('change', () => {
                const newTheme = themeToggle.checked ? 'dark' : 'light';
                this.setTheme(newTheme);
                themeLabel.textContent = themeToggle.checked ? '亮色模式' : '暗色模式';
            });
        }
        
        // 监听系统主题变化
        if (window.matchMedia) {
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
                if (savedTheme === 'system') {
                    this.setTheme('system');
                }
            });
        }
    },
    
    // 设置主题
    setTheme(theme) {
        let isDark = false;
        
        if (theme === 'system') {
            isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        } else {
            isDark = theme === 'dark';
        }
        
        if (isDark) {
            document.body.classList.add('dark-theme');
            document.body.classList.remove('light-theme');
        } else {
            document.body.classList.add('light-theme');
            document.body.classList.remove('dark-theme');
        }
        
        localStorage.setItem('theme', theme);
        
        // 更新切换按钮状态
        const themeToggle = document.getElementById('theme-toggle');
        const themeLabel = document.getElementById('theme-label');
        
        if (themeToggle && themeLabel) {
            themeToggle.checked = isDark;
            themeLabel.textContent = isDark ? '亮色模式' : '暗色模式';
        }
    }
};

// 通知系统
const notificationSystem = {
    notification: null,
    timeout: null,
    
    init() {
        this.notification = document.getElementById('notification');
        
        if (this.notification) {
            const closeBtn = this.notification.querySelector('.close-btn');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => this.hide());
            }
        }
    },
    
    // 显示通知
    show(message, type = 'info', duration = 5000) {
        if (!this.notification) return;
        
        // 清除之前的超时
        if (this.timeout) {
            clearTimeout(this.timeout);
        }
        
        // 设置消息和类型
        const messageEl = this.notification.querySelector('.message');
        if (messageEl) {
            messageEl.textContent = message;
        }
        
        // 移除所有类型类
        this.notification.classList.remove('info', 'success', 'warning', 'error');
        // 添加当前类型类
        this.notification.classList.add(type);
        
        // 显示通知
        this.notification.classList.remove('hidden');
        
        // 设置自动隐藏
        if (duration > 0) {
            this.timeout = setTimeout(() => this.hide(), duration);
        }
    },
    
    // 隐藏通知
    hide() {
        if (!this.notification) return;
        this.notification.classList.add('hidden');
        
        if (this.timeout) {
            clearTimeout(this.timeout);
            this.timeout = null;
        }
    }
};

// 标签页系统
const tabSystem = {
    init() {
        // 获取所有标签按钮
        const tabBtns = document.querySelectorAll('.tab-btn');
        
        // 为每个标签按钮添加点击事件
        tabBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const tabId = btn.getAttribute('data-tab');
                this.switchTab(btn.parentElement, tabId);
            });
        });
    },
    
    // 切换标签
    switchTab(tabContainer, tabId) {
        if (!tabContainer) return;
        
        // 获取标签容器的父元素
        const parent = tabContainer.closest('section') || document.body;
        
        // 获取所有相关的标签按钮和内容
        const tabBtns = tabContainer.querySelectorAll('.tab-btn');
        const tabContents = parent.querySelectorAll('.tab-content');
        
        // 移除所有活动状态
        tabBtns.forEach(btn => btn.classList.remove('active'));
        tabContents.forEach(content => content.classList.remove('active'));
        
        // 激活选中的标签
        tabContainer.querySelector(`[data-tab="${tabId}"]`).classList.add('active');
        parent.querySelector(`#${tabId}-tab`).classList.add('active');
    }
};

// 加载状态管理
const loadingManager = {
    overlay: null,
    
    init() {
        this.overlay = document.getElementById('loading-overlay');
    },
    
    // 显示加载状态
    show(message = '正在处理...') {
        if (!this.overlay) return;
        
        const messageEl = this.overlay.querySelector('p');
        if (messageEl) {
            messageEl.textContent = message;
        }
        
        this.overlay.classList.remove('hidden');
    },
    
    // 隐藏加载状态
    hide() {
        if (!this.overlay) return;
        this.overlay.classList.add('hidden');
    }
};

// 模态框系统
const modalSystem = {
    init() {
        // 获取所有模态框
        const modals = document.querySelectorAll('.modal');
        
        modals.forEach(modal => {
            // 关闭按钮
            const closeBtns = modal.querySelectorAll('.close-modal, .close-modal-btn');
            closeBtns.forEach(btn => {
                btn.addEventListener('click', () => this.closeModal(modal));
            });
            
            // 点击模态框外部关闭
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.closeModal(modal);
                }
            });
        });
    },
    
    // 打开模态框
    openModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('show');
            document.body.classList.add('modal-open');
        }
    },
    
    // 关闭模态框
    closeModal(modal) {
        if (typeof modal === 'string') {
            modal = document.getElementById(modal);
        }
        
        if (modal) {
            modal.classList.remove('show');
            document.body.classList.remove('modal-open');
        }
    }
};

// 工具函数
const utils = {
    // 格式化日期
    formatDate(date) {
        if (!(date instanceof Date)) {
            date = new Date(date);
        }
        
        return date.toLocaleString();
    },
    
    // 复制文本到剪贴板
    copyToClipboard(text) {
        return new Promise((resolve, reject) => {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text)
                    .then(() => resolve(true))
                    .catch(err => reject(err));
            } else {
                // 回退方法
                try {
                    const textarea = document.createElement('textarea');
                    textarea.value = text;
                    textarea.style.position = 'fixed';
                    textarea.style.opacity = '0';
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                    resolve(true);
                } catch (err) {
                    reject(err);
                }
            }
        });
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 获取文件扩展名
    getFileExtension(filename) {
        return filename.split('.').pop().toLowerCase();
    },
    
    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function(...args) {
            const context = this;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), wait);
        };
    }
};

// API服务
const apiService = {
    // 基础请求方法
    async request(endpoint, method = 'GET', data = null) {
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        };
        
        if (data) {
            if (method === 'GET') {
                const params = new URLSearchParams(data);
                endpoint = `${endpoint}?${params}`;
            } else {
                options.body = JSON.stringify(data);
            }
        }
        
        try {
            const response = await fetch(endpoint, options);
            
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `请求失败: ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('API请求错误:', error);
            throw error;
        }
    },
    
    // 生成摘要
    async summarize(text, ratio = 0.3) {
        return this.request('/api/summarize', 'POST', { text, ratio });
    },
    
    // 上传文件并生成摘要
    async summarizeFile(file, ratio = 0.3) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('ratio', ratio);
        
        try {
            const response = await fetch('/api/summarize/file', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `上传失败: ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('文件上传错误:', error);
            throw error;
        }
    },
    
    // 获取历史记录
    async getHistory(page = 1, limit = 10, search = '') {
        return this.request('/api/history', 'GET', { page, limit, search });
    },
    
    // 获取历史记录详情
    async getHistoryDetail(id) {
        return this.request(`/api/history/${id}`);
    },
    
    // 删除历史记录
    async deleteHistory(id) {
        return this.request(`/api/history/${id}`, 'DELETE');
    },
    
    // 清空历史记录
    async clearHistory() {
        return this.request('/api/history/clear', 'DELETE');
    },
    
    // 获取配置
    async getSettings() {
        return this.request('/api/settings');
    },
    
    // 保存配置
    async saveSettings(settings) {
        return this.request('/api/settings', 'POST', settings);
    }
};

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 初始化主题
    themeManager.init();
    
    // 初始化通知系统
    notificationSystem.init();
    
    // 初始化标签页系统
    tabSystem.init();
    
    // 初始化加载状态管理
    loadingManager.init();
    
    // 初始化模态框系统
    modalSystem.init();
});